package com.qqtech.qquan.user.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.PinyingUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.model.CircleMemberQuery;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserFriend;
import com.qqtech.qquan.user.model.UserFriendApply;
import com.qqtech.qquan.user.model.UserFriendQuery;
import com.qqtech.qquan.user.model.UserFriendVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserFriendApplyService;
import com.qqtech.qquan.user.service.UserFriendService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/user/friend")
public class UserFriendController extends BaseWebController<UserFriend, UserFriendQuery> {
	@Resource
	private UserFriendService userFriendService;
	@Resource
	private UserFriendApplyService userFriendApplyService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private CommunityJoinService communityJoinService;
	
	@Override
	protected BaseService<UserFriend> getBaseService() {
		return userFriendService;
	}
	
	
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Result delete(@RequestBody UserFriendApply friendApply) throws BizzException{
		Result result = new Result();
		Integer curUserId = super.getUserId();//当前用户id
		Integer friendId = friendApply.getFriendId();
		if(friendId==null){
			result.addErr("好友id为空！");
			return result;
		}
		if(!userFriendService.isFriend(curUserId, friendId)){
			result.addErr("你们还不是好友！");
			return result;
		}
		int delFriendCount = userFriendService.removeFriendShip(curUserId, friendId);
		if(delFriendCount==1){
			UserFriendApply friendApply4del = new UserFriendApply();
			friendApply4del.setUserId(curUserId);
			friendApply4del.setFriendId(friendId);
			userFriendApplyService.delete(friendApply4del);
		}
		return result;
	}
	
	/**
	 * 我的圈友
	 * @param friendQuery
	 * @return
	 */
	@RequestMapping(value = "/myFriendList")
	@ResponseBody
	public  Result myFriendList(@RequestBody UserFriendQuery friendQuery){
		Result result = new Result();
		if(super.isVisitor()){
			return result;
		}
		
		UserBaseVo userVo= null;//用于取用户呢称、头像
		Integer curUserId = super.getUserId();//当前用户id
		friendQuery.setUserId(curUserId);
		Pageable pageKit = new PageKit(friendQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<UserFriendVo> friendPage = userFriendService.queryPageList(friendQuery, pageKit);
			List<UserFriendVo> friendList = friendPage.getContent();
			if(friendList!=null && friendList.size()>0){
				for(UserFriendVo friendVo:friendList){
					
					if(friendVo.getUserId1().equals(curUserId)){//如果我是userId1,对方是userId2
						userVo  = userBaseService.getById(friendVo.getUserId2());
					}else{//如果我是userId2,对方是userId1
						userVo  = userBaseService.getById(friendVo.getUserId1());
					}
					
					List<Integer> ourCircleIds=circleMemberService.queryOurcircleIds(curUserId, userVo.getId());
					if(ourCircleIds!=null && ourCircleIds.size()>0){
						friendVo.setOurCircleCount(ourCircleIds.size());//共同加入圈子数量
					}else{
						friendVo.setOurCircleCount(0);//共同加入圈子数量
					}
					if(communityJoinService.isNeighbor(curUserId, userVo.getId())){
						friendVo.setNeighbor(true);//邻居关系
					}
					//封装一个全新的friend对象,属性意义很明确
					friendVo.setFriendId(userVo.getId());
					friendVo.setFriendName(StringUtil.isNotBlank(userVo.getNick())?userVo.getNick():"新手");
					friendVo.setFriendLogo(StringUtil.isNotBlank(userVo.getLogo())?userVo.getLogo():"source://image/common/userLogin.png");
					friendVo.setSex(userVo.getSex());
					//兴趣：这里如果不处理一下，就会返回null给ui,null是不会覆盖ui的属性的,会导致 圈友的兴趣错乱
					friendVo.setInterests(StringUtil.isBlank(userVo.getInterests()) ? "" : userVo.getInterests());
				}
			}
		
		result.put("friendPage", friendPage);
		return result;
	}
	
	/**
	 * 我的圈友(不分页,带首字母)
	 * @param friendQuery
	 * @return
	 */
	@RequestMapping(value = "/myFriendMap")
	@ResponseBody
	public  Result myFriendMap(@RequestBody UserFriendQuery friendQuery){
		Result result = new Result();
		if(super.isVisitor()){
			return result;
		}
		UserBaseVo userVo= null;//用于取用户呢称、头像
		Integer curUserId = super.getUserId();//当前用户id
		friendQuery.setUserId(curUserId);
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE ,new PageOrder(Direction.ASC, "id"));
		List<UserFriendVo> friendList = userFriendService.queryList(friendQuery, pageKit);
		if(friendList!=null && friendList.size()>0){
			List<Integer> myFriendIds = userFriendService.queryMyFriendIds(curUserId);
			LinkedHashMap<Integer, UserBaseVo> userMap = userBaseService.queryUserMapListByUserIds(myFriendIds);
			for(UserFriendVo friendVo:friendList){
				if(friendVo.getUserId1().equals(curUserId)){//如果我是userId1,对方是userId2
					userVo  = userMap.get(friendVo.getUserId2());
					friendVo.setRemark(friendVo.getRemark1());
					friendVo.setChnSpell(friendVo.getChnSpell1());
				}else{//如果我是userId2,对方是userId1
					userVo  = userMap.get(friendVo.getUserId1());
					friendVo.setRemark(friendVo.getRemark2());
					friendVo.setChnSpell(friendVo.getChnSpell2());
				}
				if(userVo!=null){
					List<Integer> ourCircleIds=circleMemberService.queryOurcircleIds(curUserId, userVo.getId());
					if(ourCircleIds!=null && ourCircleIds.size()>0){
						friendVo.setOurCircleCount(ourCircleIds.size());//共同加入圈子数量
					}else{
						friendVo.setOurCircleCount(0);//共同加入圈子数量
					}
					if(communityJoinService.isNeighbor(curUserId, userVo.getId())){
						friendVo.setNeighbor(true);//邻居关系
					}
					//封装一个全新的friend对象,属性意义很明确
					friendVo.setFriendId(userVo.getId());
					friendVo.setFriendName(userVo.getNick());
					friendVo.setFriendLogo(userVo.getLogo());
					friendVo.setSex(userVo.getSex());
					if(StringUtil.isBlank(friendVo.getChnSpell())){
						friendVo.setChnSpell(userVo.getChnSpell());//全拼
					}
					if(!friendVo.getFirstChar().matches("[A-Z]")){
						//如果字符不是大写字母，设为#
						friendVo.setChnSpell("#");
					}
					if(StringUtil.isBlank(friendVo.getRemark())){
						friendVo.setRemark(friendVo.getFriendName());//如果没有备注，取用户昵称
					}
					//兴趣：这里如果不处理一下，就会返回null给ui,null是不会覆盖ui的属性的,会导致 圈友的兴趣错乱
					friendVo.setInterests(StringUtil.isBlank(userVo.getInterests()) ? "" : userVo.getInterests());
				}
				
			}
		}
		// 转化为有序的map
		LinkedHashMap<String, List<UserFriendVo>> map = new LinkedHashMap<String, List<UserFriendVo>>();
		if(friendList!=null && friendList.size()>0){
			Collections.sort(friendList, new Comparator<UserFriendVo>() {
				public int compare(UserFriendVo arg0, UserFriendVo arg1) {
					return arg0.getFirstChar().compareTo(arg1.getFirstChar());// 升序
				}
			});
			for(UserFriendVo friendVo:friendList){
				if (null == map.get(friendVo.getFirstChar())) {
					List<UserFriendVo> aList = new ArrayList<UserFriendVo>();
					aList.add(friendVo);
					map.put(friendVo.getFirstChar(), aList);
				} else {
					List<UserFriendVo> aList = (List<UserFriendVo>) map.get(friendVo.getFirstChar());
					aList.add(friendVo);
				}
			}
		}
		
		result.put("friendMapKeys", map.keySet());
		result.put("friendMap", map);
		return result;
	}
	
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/myFriendOutOfCircle")
	@ResponseBody
	public  Result myFriendOutOfCircle(@RequestBody CircleMemberQuery memberQuery){
		Result result = new Result();
		UserBaseVo userVo= null;//用于取用户呢称、头像
		Integer curUserId = super.getUserId();//当前用户id
		Integer circleId = memberQuery.getCircleId();
		if(circleId==null){
			result.addErr("圈子id为空!");
			return result;
		}
		UserFriendQuery friendQuery = new UserFriendQuery();
		friendQuery.setPage(memberQuery.getPage());
		friendQuery.setUserId(curUserId);
		
		Pageable pageKit = new PageKit(1, new PageOrder(Direction.DESC, "id"));
		List<UserFriendVo> friendList = userFriendService.queryList(friendQuery, pageKit);
			if(friendList!=null && friendList.size()>0){
				for(UserFriendVo friendVo:friendList){
					if(friendVo.getUserId1().equals(curUserId)){//如果我是userId1,对方是userId2
						userVo  = userBaseService.getById(friendVo.getUserId2());
					}else{//如果我是userId2,对方是userId1
						userVo  = userBaseService.getById(friendVo.getUserId1());
					}
					//封装一个全新的friend对象,属性意义很明确
					friendVo.setFriendId(userVo.getId());
					friendVo.setFriendName(userVo.getNick());
					friendVo.setFriendLogo(userVo.getLogo());
					friendVo.setSex(userVo.getSex());
					friendVo.setInterests(userVo.getInterests());
					friendVo.setCircleMember(circleMemberService.isCircleMember(userVo.getId(), circleId));//是否圈子成员
				}
			}
		
		result.put("friendList", friendList);
		return result;
	}
	
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/addRemark")
	@ResponseBody
	public Result addRemark(@RequestBody UserFriendQuery friendQ) throws BizzException{
		Result result = new Result();
		Integer curUserId = super.getUserId();//当前用户id
		Integer herUserId = friendQ.getUserId();//好友的id
		String remark = friendQ.getRemark();//好友备注
		if(herUserId==null){
			result.addErr("圈友id为空！");
			return result;
		}
		if(StringUtil.isBlank(remark)){
			result.addErr("请添加备注！");
			return result;
		}
		UserFriendVo friend = userFriendService.queryNormalFriend(curUserId, herUserId);
		if(friend == null){
			result.addErr("你们还不是圈友！");
			return result;
		}
		String pinYin4Remark = PinyingUtil.hanziToPinyinNoSpace(remark).toUpperCase();//备注-全拼
		UserFriend friend4update = new UserFriend();
		friend4update.setId(friend.getId());//key
		if(curUserId.intValue() == friend.getUserId1().intValue()){//如果我是user1
			friend4update.setRemark1(remark);
			if(StringUtil.isNotBlank(pinYin4Remark)){
				friend4update.setChnSpell1(pinYin4Remark);//全拼大写
			}
		}else{//如果我是user2
			friend4update.setRemark2(remark);
			if(StringUtil.isNotBlank(pinYin4Remark)){
				friend4update.setChnSpell2(pinYin4Remark);//全拼大写
			}
		}
		userFriendService.updateById(friend4update);
		return result;
	}
}
